import {messages, getQueryUrlParam} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Form, Button, message, Modal, Icon} from 'antd'
import approveOtherService from 'containers/approve/other/other.service'
import ApproveBar from 'components/template/approve-bar'
import 'styles/approve/request/approve-request-btn.scss'

class ApproveOtherBtn extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      passLoading: false,
      rejectLoading: false,
      info: {}, //其他单详情
      approvalChain: {},  //审批链
      showAdditionalBtn: false,  //是否显示加签按钮
      preApproveOIDs: [], //当前审批链中已审批用户的OID
      // TODO 只改了废弃的key，还需修改返回逻辑
      approveOtherList: menuRoute.getRouteItem('to-be-approve', 'key'), //其他单审批列表页
      signCompanyOIDs:[]
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!this.state.info.entityOID && nextProps.approving) {
      const formInfo = nextProps.formInfo;
      this.setState({
        info: nextProps.info
      }, () => {
        this.showAdditional();
        this.getPreApproveOID();
      })
    }
  }

  //判断是否可以加签
  showAdditional = () => {
    let params = {
      companyOID: this.props.company.companyOID,
      formOID: this.state.info.formOID,
      counterSignType: 'enableAddSign',
    };
    this.props.approving && this.state.info.formOID && (
      approveOtherService.postAddSignEnableScope(params).then(res =>{
        if (res.data.enabled) {
          //加签人范围
          this.setState({
            showAdditionalBtn: res.data.enabled,
            signCompanyOIDs: res.data.approvalAddSignScope.companyOIDs
          });
        }
      })
    )
  };

  //获取当前审批链中已审批的用户OID
  getPreApproveOID = () => {
    let preApproveOIDs = [];
    (this.state.info.approvalHistorys || []).map(item => {
      item.operation === 2001 && (preApproveOIDs.push(item.operatorOID));
    });
    this.setState({ preApproveOIDs });
  };

  //提示 当前被加签的人是否在已审批的人中
  hasRepeatApproveTip = (value, additionalItems, priceAuditor) => {
    let additionalOIDs = [];
    let additionalHaveApprovedNames = [];  //加签人中已审批的用户名
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID);
    });
    additionalOIDs.map((OID, index) => {
      if (this.state.preApproveOIDs.indexOf(OID) > -1) {
        additionalHaveApprovedNames.push(additionalItems[index].fullName);
      }
    });
    if (additionalHaveApprovedNames.length) {
      Modal.confirm({
        title: `${additionalHaveApprovedNames.join('、')} ${messages('approve.key86'/*已经审批通过，是否继续*/)}？`,
        onOk: () => this.handleApprovePass(value, additionalOIDs, priceAuditor)
      });
    } else {
      this.handleApprovePass(value, additionalOIDs, priceAuditor);
    }
  };

  //审批通过
  handleApprovePass = (value, additionalOIDs, priceAuditor) => {
    let params = {
      approvalTxt: value,
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: this.state.info.entityOID,
        entityType: 4001, //其他单
        countersignApproverOIDs: additionalOIDs,
        priceAuditor
      }]
    };
    this.setState({ passLoading: true });
    approveOtherService.handleOtherApprovePass(params).then(res => {
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success'));
        this.setState({ passLoading: false });
        this.goBack()
      } else {
        this.setState({ passLoading: false });
        message.error(`${messages('common.operate.filed')}，${res.data.failReason[this.state.info.entityOID]}`)
      }
    }).catch(e => {
      this.setState({ passLoading: false });
      message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
    })
  };

  //审批驳回
  handleApproveReject = (value, additionalItems) => {
    let additionalOIDs = [];
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID)
    });
    let params = {
      approvalTxt: value,
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: this.state.info.entityOID,
        entityType: 4001, //其他单
      }]
    };
    this.setState({ rejectLoading: true });
    approveOtherService.handleOtherApproveReject(params).then(res => {
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success'));
        this.setState({ rejectLoading: false });
        this.goBack()
      } else {
        this.setState({ rejectLoading: false });
        message.error(`${messages('common.operate.filed')}，${res.data.failReason[this.state.info.entityOID]}`)
      }
    }).catch(e => {
      this.setState({ rejectLoading: false });
      message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
    })
  };

  //返回
  goBack = () => {
    const {approveOtherList} = this.state;
    let backUrl = this.props.backUrlKey ? this.getKeyUrl(this.props.backUrlKey) : approveOtherList.url + '?tab=approving';
    this.context.router.push(backUrl);
  };

  getKeyUrl = (key) => {
    let urlInfo = menuRoute.getRouteItem(key, 'key');
    return urlInfo.url;
  };

  render() {
    const { passLoading, rejectLoading, approveOtherList, showAdditionalBtn, signCompanyOIDs } = this.state;
    let moreButtons = [];
    showAdditionalBtn && moreButtons.push('additional');
    let backUrl = this.props.backUrlKey ? this.getKeyUrl(this.props.backUrlKey) : approveOtherList.url + '?tab=approving';
    return (
      <div className="approve-request-btn">
        {this.props.approving ? (
          <ApproveBar backUrl={backUrl}
                      signCompanyOIDs={signCompanyOIDs}
                      moreButtons={moreButtons}
                      passLoading={passLoading}
                      rejectLoading={rejectLoading}
                      customFormPropertyMap={this.props.formInfo ? this.props.formInfo.customFormPropertyMap : {}}
                      entities={{
                        approverOID: getQueryUrlParam('approverOID'),
                        entityOID: this.state.info.entityOID,
                        entityType: 4001,
                      }}
                      handleApprovePass={this.hasRepeatApproveTip}
                      handleApproveReject={this.handleApproveReject}/>
        ) : (
          <div>
            <Button onClick={this.goBack} className="back-btn">{messages("common.back")/*返回*/}</Button>
          </div>
          )}
      </div>
    )
  }
}

ApproveOtherBtn.propTypes = {
  formType: React.PropTypes.number,
  info: React.PropTypes.object,
  formInfo: React.PropTypes.object,
  approving: React.PropTypes.bool,
  backUrlKey: React.PropTypes.string //返回URLKey 修改人：陈行健
};

ApproveOtherBtn.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    profile: state.login.profile
  }
}

const wrappedApproveOtherBtn = Form.create()(ApproveOtherBtn);

export default connect(mapStateToProps)(wrappedApproveOtherBtn)
